﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mani.Patient.Business.Domain.Entity;
using NHibernate;
using NHibernate.Expression;

namespace Mani.Patient.Business.Dao {

    public interface IFileDao : IDao<File> {

        string GetNextFileNumber(string fileNumberLike);
        File FindByFileNumber(string fileNumber);
    }

    public class FileDao : DaoBase<File>, IFileDao {

        public string GetNextFileNumber(string fileNumberLike) {

            ICriteria criteria = base.Session.CreateCriteria(typeof(File));
            criteria.Add(Expression.Like("FileNumber", fileNumberLike, MatchMode.Start));
            criteria.SetProjection(Projections.Max("Id"));
            object i = criteria.UniqueResult();

            if ( i == null )
                return (fileNumberLike + "001");

            File f = base.FindById(Convert.ToInt32(i));
            
            return ((Convert.ToInt32(f.FileNumber)) + 1).ToString();
        }

        public File FindByFileNumber(string fileNumber) {
            ICriteria criteria = base.Session.CreateCriteria(typeof(File));
            criteria.Add(Expression.Eq("FileNumber", fileNumber));

            return criteria.UniqueResult<File>();
        }
    }
}
